import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component, ElementRef, EventEmitter, HostListener, Input, OnInit, Output, Renderer2, SimpleChanges, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core';
import { UploadXHRArgs } from 'ng-zorro-antd/upload';

import { CaseReviewService } from '../../../../../@core/service/case-review/case-review.service';
import { DocgenService} from '../../../../../@core/service/case-review/doc-select/api/docgen.service';
import { BizfileService } from '../../../../../@core/service/case-review/doc-service/api/bizfile.service';
import { ClueDataService } from '../../../../../@core/service/clue-service/clue-data.service';
import { CaseService } from '../../../../../@core/service/handle-service/api/case.service';
import { StakeHolderService } from '../../../../../@core/service/handle-service/api/stakeHolder.service';
import { ApprovalInfoModel } from '../../../../../@core/service/handle-service/model/approvalInfoModel';
import { ApprovalInfoModelCmsCase } from '../../../../../@core/service/handle-service/model/approvalInfoModelCmsCase';
import { ApprovalInfoModelStakerHolderList } from '../../../../../@core/service/handle-service/model/approvalInfoModelStakerHolderList';
import { SYSTEMService } from '../../../../../@core/service/login-service/api/sYSTEM.service';
import { OrgService } from '../../../../../@core/service/person-select-service/api/org.service';
import { ClueService } from '../../../../../@core/service/typescript-angular-client/api/clue.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CaseDocService } from '../../../../../@core/service/handle-service/api/caseDoc.service';
import {EvidenceService} from '../../../../../@core/service/evidence/api/evidence.service';

import { DomSanitizer } from '@angular/platform-browser'; // 引入DomSanitizer服务

import { VgAPI, VgPlayer } from 'videogular2/compiled/core';


@Component({
  selector: 'app-handelfullstaff',
  templateUrl: './handelfullstaff.component.html',
  styleUrls: ['./handelfullstaff.component.scss'],
  animations: [
    trigger('expandShrink', [
      state('expand', style({
        height: '233px',
        // opacity: 1
      })),
      state('shrink', style({
        height: '10px',
        // opacity: 0.5
      })),
      transition('shrink => expand', [
        animate('0.2s'),
      ]),
      transition('expand => shrink', [
        animate('0.2s'),
      ]),
    ]),
  ],
})
export class HandelfullstaffComponent implements OnInit {

  constructor(
    public render: Renderer2,
    public http: HttpClient, // 自定义上传证据
    public evidence: EvidenceService, // 证据上传service
    private sanitizer: DomSanitizer, // 安全连接service
    public caseservice: CaseService,
    public bizfile: BizfileService,
    public docgen: DocgenService,
    public caseReview: CaseReviewService,
    private systemService: SYSTEMService,
    private orgService: OrgService,
    private stakeHolderService: StakeHolderService,
    public clueData: ClueDataService,
    public router: Router,
    public active: ActivatedRoute,
    public clue: ClueService,
    public message:NzMessageService,
    public caseDocService:CaseDocService
  ) {

  }

  @Output('expandAnimationFlag') expandAnimation = new EventEmitter<any>();

  @Input() sendMsg;

  @Input() stakerHolder: any[];
  // 选中文书
  public DocumentId: string;
  // 返回文书列表
  public DocumentList: any[];

  // 案件ID
  public ajId: any;

  @Input() public name: any;
  @Output() senddoc = new EventEmitter();
  @Output() sendFather = new EventEmitter();
  @Input() clueList: any;
  @Input() clueDoc: any;
  @Input() isExpand: boolean;

  @ViewChild('save') save: any;

  private session = sessionStorage;

  public url = null; // 播放
  public safeUrl: any;
  // 线索id
  clueId: string;

  api: VgAPI;
  // 所有文书
  public dataList: any;
  // 类型为其他的文书
  public bizfileListOther: any[];
  // 类型不为其他的文书
  public bizfileList: any[];

  public newDocument: any;
  public loading = false;
  public id: any;
  public type: string;

  public currentLink: any;

  public remark: any; // 子组件备注

  public listOfTagOptions: any; // 选择的审批文书
  public sourceOrgId: any;
  public sourceDeptId: any;
  public sourceUserId: any;

  public mechanism = null;
  public dept = null;
  public person = null;

  public fileList = null; // 附件列表

  expandKeys = [];  // 默认展开的节点
  targetOrg: string;
  nodes = [];
  listOfOption = [];
  personOptionList = [];
  getPersonSelectedValue = [];
  selectedValue = null;
  selectedPersonValue = [];
  // 按钮标识
  public btnPerssion: any = {};
  // 文书上传

/***********************查看证据详情**************************** */
  public isVisible = false; // 证据查看
  public isVisibleUpload = false; // 证据上传
  // 是否展示文件列表
  // 证据上传案件环节
  public currentLinkUpload = null;

  // 证据查看
  public publictypeFlagVideo = null; // 视频判断
  public publictypeFlagAudio = null; // 音频判断
  public publictypeFlagImage = null; // 图片判断
  public fileId: any = null; // 证据的文件ID
  // 证据 文书判断条件
  public choose: string;

  //  修改标题

    public fileNameIndex = null; // 保存编辑按钮切换
    public newValue = null;
  onPlayerReady(api: VgAPI) {
    this.api = api;
    this.api.getDefaultMedia().subscriptions.ended.subscribe(
      () => {
        // Set the video to the beginning
        this.api.getDefaultMedia().currentTime = 0;
      },
    );
  }

  getUrl(url: string) {
    this.safeUrl = this.sanitizer.bypassSecurityTrustUrl(url);  // 获取安全链接
  }

  ngOnInit() {
    if (this.active.snapshot.params['id']) {
      this.id = this.active.snapshot.params['id'];
      this.type = this.active.snapshot.params['type'];
      
      if (this.type === 'approval') {
        this.btnPerssion = {
          insert: 'approval_document_insert',     // 新建文书
          upload: 'approval_document_upload',      // 文书上传
          select: 'approval_select',               // 查看
          evidence: 'approval_upload_evidence',    // 上传证据
          approval: 'approval_approval',           // 审批
          download: 'approval_upload',             // 下载
          delete: 'approval_delete',               // 删除
          choice: 'approval_choice_doc',            // 选择文书
        };
      } else {
        this.btnPerssion = {
          insert: 'handle_document_insert',     // 新建文书
          upload: 'handle_document_upload',      // 文书上传
          select: 'handle_select',               // 查看
          evidence: 'handle_upload_evidence',    // 上传证据
          approval: 'handle_approval',           // 审批
          download: 'handle_upload',             // 下载
          delete: 'handle_delete',               // 删除
          choice: 'handle_choice_doc',            // 选择文书
        };
      }

      const nodesData = JSON.parse(this.session.getItem('areaData'));
      this.nodes = this.DataProcess(nodesData, '0', '机构');
      const roleInfo = JSON.parse(this.session.getItem('roles'));
      for (let i = 0; i < roleInfo.length; i++) {
        if (roleInfo[i]['roleName'] === '局长') {
          this.getDefualtHandlePerson(this.id);
        }
      }
    }

    // 初始化获取文书列表
    this.docgen.docgenAllFiletypeGet().subscribe((data) => {
      this.DocumentList = data;
    });
    // 查询证据列表
    this.checkEvidence();
    if (this.name === 'previewdocument') {
      this.queryDocByPage(this.id);
    }
  }
  // 用户角色为局长的时候查询默认办案人员
  getDefualtHandlePerson(id) {
    this.stakeHolderService.stakeHolderTargetCaseIdGet(id).subscribe((data) => {
      if (data['rel']) {
        this.targetOrg = data['data'][0]['targetOrgId'];
        this.selectedValue = data['data'][0]['targetDeptId'];
        this.selectedPersonValue = [data['data'][0]['targetUserId']];
        let parentId: string;
        for (let i = 0; i < this.nodes.length; i++) {
          const children = this.nodes[i]['children'];
          for (let k = 0; k < children.length; k++) {
            if (this.targetOrg === children[k]['value']) {
              parentId = children[k]['parentId'];
            }
          }
        }
        this.expandKeys = [parentId, this.targetOrg];
        this.getSelectedNodeList(this.targetOrg);
        this.getPerson(this.selectedValue);
      }
    }, (error) => {
    });
  }

  // 底部卡片展开与收起
  cardToggle() {
    this.isExpand = !this.isExpand;
    this.expandAnimation.emit(this.isExpand);
  }
  // 关闭卡片
  closeCard() {
    this.isExpand  = false;
    this.expandAnimation.emit(this.isExpand);
  }
  // 打开卡片
  openCard() {
    this.isExpand = true;
    this.expandAnimation.emit(this.isExpand);
  }



  // 将后台返回的数据处理成符合树形结构
  DataProcess(data, parentId, type) {
    const arrayList = [];
    for (let i = 0; i < data.length; i++) {
      if (data[i]['orgTypeName'] === type && data[i]['orgParentId'] === parentId) {
        const obj = {
          title: '',
          text: '',
          value: '',
          key: '',
          parentId: '',
          children: [],
        };
        obj.title = data[i]['orgName'] || '';
        obj.text = data[i]['orgName'] || '';
        obj.value = data[i]['orgId'] || '';
        obj.key = data[i]['orgId'] || '';
        obj.parentId = data[i]['orgParentId'] || '';
        obj.children = this.DataProcess(data, obj.value, '机构');
        if (obj.children.length <= 0) {
          obj['isLeaf'] = true;
        }
        arrayList.push(obj);
      }
    }
    return arrayList;
  }
  // 获取树中选中的节点
  getSelectedNodeList(key): void {
    this.systemService.authOrgDeptsOrgIdGet(key).subscribe((res) => {
      if (res['rel']) {
        this.listOfOption = res['data'];
      }
    }, (error) => {
    });
  }

  // 获取部分选择框选中的节点
  getSelectedValue(value): void {
    this.selectedValue = value;
    const token = this.session.getItem('accessToken') || '';
    for (let i = 0; i < this.listOfOption.length; i++) {
      if (this.listOfOption[i]['deptId'] === value) {
        this.getPerson(value);
      }
    }
  }

  // 获取人员信息
  getPerson(deptId) {
    this.systemService.authDeptUsersDeptIdGet(deptId).subscribe((res) => {
      if (res['rel'] === true) {
        this.personOptionList = [];
        for (let i = 0; i < res['data'].length; i++) {
          const obj = {realName: null, positionCode: null, userId: null, userType: null};
          obj.realName = res['data'][i]['realName'] || '';
          obj.positionCode = res['data'][i]['positionCode'] || '';
          obj.userId = res['data'][i]['userId'] || '';
          obj.userType = res['data'][i]['roles'] || [];
          this.personOptionList.push(obj);
        }
      }
    }, (error) => {
    });
  }
  selectedPerson(users: []) {

  }
  ngOnChanges(changes: SimpleChanges): void {
    if (this.sendMsg) {
      this.ajId = this.sendMsg.id;
      this.queryDocByPage(this.ajId);
    }
  }

  queryDocByPage(id) {
    this.bizfile.queryDocByPage(id, 1, 1000).subscribe((data) => {
      this.dataList = data.data.data;
      this.caseReview.setBizfile(this.dataList);
      this.bizfileListOther = this.dataList.filter((item) => item.doctype === '其他');
      this.bizfileList = this.dataList.filter((item) => item.doctype !== '其他');
      this.caseservice.caseIdIdGet(this.id).subscribe((casedata) => {
        if (casedata.data) {
          this.clueId = casedata.data.clueId;
        }
      });
    });
  }
  // 机构选择
  onMechanismChange(event) {

    if (event !== null) {

    } else {
      this.dept = null;
      this.person = null;
    }
  }
   // 部门选择
   onDeptChange(event) {
    if (event !== null) {

    } else {
      this.person = null;
    }
   }
   // 人员选择
   onPersonChange(event) {
     if (event !== null) {

     } else {
       this.clueList.address.county = null;
     }
   }

   findArea(areas,parentId,areaName,areaId){
    for(let i = 0; i<areas.length;i++){
       if(areas[i].areaParentId == parentId){
           areaName.push(areas[i].areaName);
           areaId.push(areas[i].areaId);
           this.findArea(areas,areas[i].areaId,areaName,areaId) 
       }
    }
    }
    findAreaCode(areas,areaId){
      for(let i =0;i<areas.length;i++){
        if(areas[i].areaId == areaId){
            return areas[i].areaCode;
        }
      }
    }
   
  mysubmit() {
    if (!this.dataList) {
      alert('请先保存并生成文书');
    } else {  
      const id = this.id;
      const currentLink = this.currentLink;
      const currentHandlePerson: any[] = this.selectedPersonValue;
      const remark = this.remark;
      const approvalDocStr = this.listOfTagOptions ? this.listOfTagOptions.join(',') : '';
      const targetOrgId = this.targetOrg;
      const targetDeptId = this.selectedValue;
      let sourceOrgId = '';
      let sourceDeptId = '',sourceOrgName = '',areaName=[],areaId=[];
         // 获取部门
         let departments =  JSON.parse(this.session.getItem('departments'));
         // 获取机构
         let organization = JSON.parse(this.session.getItem('organizations'))[0];
         // 获取行政区划
         let areas = JSON.parse(this.session.getItem('areas'));
         sourceOrgId = organization['orgId']
         sourceOrgName = organization['orgName'];
         this.findArea(areas,'0',areaName,areaId) 
          const cmsCase: ApprovalInfoModelCmsCase = {
            id,
            remark,
            approvalDocStr,
            currentHandlePerson: this.selectedPersonValue[0],
            // currentHandlePersonName: sessionStorage.getItem('realName'),
            // currentHandleOrgId : sourceOrgId,
            // currentHandleOrgName: sourceOrgName,
            // currentHandleAreaNo: this.findAreaCode(areas,areaId[areaId.length-1]),
            // currentHandleAreaName: areaName[areaName.length-1]
          };
      const stakerHolderList: ApprovalInfoModelStakerHolderList[] = [];
      for (let i = 0; i < currentHandlePerson.length; i++) {
        const obj: ApprovalInfoModelStakerHolderList = {
          sourceOrgId,
          sourceDeptId,
          sourceUserId: this.session.getItem('userId'),
          targetOrgId,
          targetDeptId,
          targetUserId: '',
          stage: currentLink,
          userType: null,
          serial: (i + 1).toString(),
        };
        const userType: any[] = [];
        for (let j = 0; j < this.personOptionList.length; j++) {
          if (this.personOptionList[j]['userId'] === currentHandlePerson[i]) {
            const role = this.personOptionList[j]['userType'];
            for (let k = 0; k < role.length; k++) {
              userType.push(role[k]['roleName']);
            }
            obj['userType'] = userType.join(',');
          }
        }
        obj['targetUserId'] = currentHandlePerson[i];
        stakerHolderList.push(obj);
      }

      const approvalInfoModel: ApprovalInfoModel = {
        cmsCase,
        stakerHolderList,
      };
      this.caseservice.caseProcessPut(approvalInfoModel).subscribe((data) => {
        if (data['rel']) {
          this.router.navigate(['/main/home/handle']);
        } else {
          alert(data['message']);
        }
      }, (error) => {
      });
    }
  }
  back() {
  
    if(this.active.snapshot.data.type == 'handle'){
      this.router.navigate(['/main/home/handle']);
    }else if(this.active.snapshot.data.type == 'approval'){
      this.router.navigate(['/main/home/approval']);
    }else {
      this.router.navigate(['/main/home/handle']);
    }
  }
  customModelChange(event) {

  }

 // 审批事件
 approval(docid, doctype): void {
  this.caseReview.setShowWindow(true);
  this.caseReview.getCreateCaseDoc().emit({condition: 'Approval', docid, doctype, bizid: this.id, callback: this.queryDocByPage.bind(this)});
}
  // 新建文书
  newDocuments() {
    if (this.DocumentId) {
      this.caseReview.setShowWindow(true);
      this.caseReview.getCreateCaseDoc().emit({condition: 'New', docid: null, doctype: this.DocumentId, bizid: this.id, callback: this.queryDocByPage.bind(this)});
    }
  }
  // 文书编辑
  handleEdit(docid, doctype): void {
    if (doctype === '案件来源登记表') {
      this.router.navigate(['/main/home/handle/edithandle', this.id, docid,'handle']);
      return;
    }
    this.caseReview.setShowWindow(true);
    this.caseReview.getCreateCaseDoc().emit({condition: 'New', docid, doctype, bizid: this.id, callback: this.queryDocByPage.bind(this)});
  }
  // 文书选择列表
  docSelect(event) {
      if (event === '其他') {

      } else {

      }
  }
  showModal(contentType, fileId, condition): void {
    this.isVisible = true;
    this.fileId = fileId;
    this.publictypeFlagVideo = contentType.includes('video');
    this.publictypeFlagAudio = contentType.includes('audio');
    this.publictypeFlagImage = contentType.includes('image');
    
    if (condition === 'evidence') {
      this.url = '/evidenceApi/evidence/file/' + this.fileId;
    } else {
      this.url = '/download/bizfile/' + this.fileId;
    }
    if (this.publictypeFlagImage) {
      this.loading = true;
      const img = new Image();
      img.src = this.url;
      img.onload = () => {
        this.loading = false;
      };
    } else if (this.publictypeFlagAudio) {

    } else if (this.publictypeFlagVideo) {

    }
  }
  handleOk(): void {
    this.isVisible = false;
  }
  handleCancel(): void {
    this.isVisible = false;
  }

  // 证据 & 文书 上传弹框
  showModalUpload(choose): void {
    this.choose = choose;
    this.isVisibleUpload = true;
  }
  // 证据 & 文书 关闭按钮
  handleCancelUpload(): void {
    this.isVisibleUpload = false;
    this.fileNameIndex = null;
    this.newValue = null;

  }
  // 选择文件上传
  public customReq = (item: any) => {
    // Create a FormData here to store files and other parameters.
  //  console.log(item)

   this.fileNameIndex = null;
   if (this.choose === 'evidence') {
    this.evidence.evidenceFilePost(this.id, item.file, this.currentLinkUpload, this.session.getItem('userId')).subscribe((data) => {
      if (data.code === 200) {

        this.fileList = data.data;
        this.currentLinkUpload = null;
      }
    });
   } else if (this.choose === 'bizfile') {
      this.bizfile.saveUploadBizFile(this.id, '其他', item.file.name, item.file, this.currentLinkUpload).subscribe((data) => {
         if (data.code === 4) {
            this.queryDocByPage(this.id);
         }
      });
   }
 }
 checkEvidence(): void {
      // 查询案件证据列表
      if (this.id) {
        this.evidence.evidenceObjectIdObjectIdGet(this.id).subscribe((data: any) => {
          this.fileList = data.data;
          this.caseReview.setEvidence(this.fileList);
        });
      }
 }
  // 删除 文件 & 证据单个数据
  deleteFile(id: string): void {
    if (this.choose === 'evidence') {
      this.evidence.evidenceIdDelete(id).subscribe((data: any) => {
        this.checkEvidence();
      });
    } else if (this.choose === 'bizfile') {
      this.caseDocService.bizfileDelete('0',id,this.id).subscribe((data: any) => {
        this.queryDocByPage(this.id);
      });
    }
}
// 删除文书
deleteBizfile(id: string): void {
  this.caseDocService.bizfileDelete('0',id,this.id).subscribe((data: any) => {
    this.queryDocByPage(this.id);
  });
}

// 删除证据
deleteEvidence(id: string): void {
  this.evidence.evidenceIdDelete(id).subscribe((data: any) => {
    this.checkEvidence();
  });
}

downLoad(fileid,fileName,downloadText) {
  if(downloadText === 'bizfile'){
    this.bizfile.downloadFile(fileid).subscribe((res:any) => {
      this.createA2Click(res,fileName)
    }, (error) => { 
      this.message.create('error','文书下载失败！')
    });
  }else if(downloadText === 'evidence'){
    this.evidence.evidenceFileIdGet(fileid).subscribe((res:any)=>{
        this.createA2Click(res,fileName)
    },(error)=>{
      this.message.create('error','证据下载失败！')
    })
  }
}

createA2Click(res,fileName){
    const fileURL = URL.createObjectURL(res);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = fileName;
    a.href = fileURL;
    a.click();
  }
// 结案
  completion(){
    if (!this.dataList) {
      alert('请先保存并生成文书');
    }else{
      this.caseservice.caseCompletionPut(this.id,this.remark).subscribe((res)=>{
        console.log(res);
        if(res){
          this.message.create('success', `结案成功`);
          this.router.navigate(['/main/home/handle']);
        }
      })
    }
  }

  changeTag(index, item) {
    this.fileNameIndex = index;
    const newnode = document.createElement('input');

    // newnode.setAttribute("value", item.filename)
    const oldnode =  document.getElementsByClassName('changedTag')[index];
    const fileHz = this.choose === 'bizfile' ? item.filename.substring(item.filename.lastIndexOf('.')) : oldnode.innerHTML.substring(oldnode.innerHTML.lastIndexOf('.'));  // 切除后缀
    newnode.value = oldnode.innerHTML.substring(oldnode.innerHTML.lastIndexOf('.'), -1);
    oldnode.parentNode.replaceChild(newnode, oldnode);
    newnode.focus();
    newnode.addEventListener('blur', () => {
    newnode.parentNode.replaceChild(oldnode, newnode);
    if ( newnode.value + fileHz === item.fileName) {
      this.fileNameIndex = null;
     } else {
      oldnode.innerHTML = newnode.value + fileHz;
     }
    this.newValue =  newnode.value + fileHz;
    });
  }
  saveName(index, item) {
    // 保存方法
    item.fileName = this.newValue;
    if (this.choose === 'evidence') {
      this.evidence.evidencePut(item).subscribe((data: any) => {
        this.fileNameIndex = null;
        this.checkEvidence();
      });
    } else if (this.choose === 'bizfile') {
      this.bizfile.modifyFileName(item.fileid, item.fileName).subscribe((data: any) => {
        this.fileNameIndex = null;
        this.queryDocByPage(this.id);
      });
    }
  }
}
